#!/bin/bash
#THIS DRIVER WRITTEN BY MATTHEW VONA ARB FOR THE RMYOUNG81000 ULTRASONIC ANEMOMETER
#FOR QUESTIONS WRITE mailto:mvona@arb.ca.gov
# THIS IS THE FUNCTION CALLED IN THE EVENT THAT CTRL+C IS PRESSED
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

#COMMAND TO RUN WHEN WANTING TO REMOVE ALL SUB-SECOND FILES
clean_temp_data()
{
	for i in `seq -w 00 24`
		do
			rm -R ${DIR}/${i} 1> /dev/null 2>/dev/null
		done
}
#COMMAND TO RUN PRIOR TO DATA COLLECTION TO ENSURE THAT NO OLD DATA EXISTS
pre_run()
{
	clean_temp_data
	#set_config
	:
}
pre_run


#INITIALIZE THE LGR RECORDER
record()
{
bash ${DIR}/rmcord "${dvc_prt}" "${bd_rt}"&
rm_id="$!"
if [ -z "$rm_id" ]
then 
	echo "Failed to start the LGR recorder."
fi
#if !(bash ${DIR}/rmcord "${dvc_prt}" "${bd_rt}"&); then
#	{
#		echo "Failed to start the RMYOUNG recorder."
#	}
#else
#	{
#		#DETERMINE THE IS OF THE rmcord PROCESS
#		rm_id=`ps -fe | grep rmcord | grep -v grep | awk '{ print $2 }'`	
#		echo "RMCORD IS $rm_id"
#	}
#fi
}
#GET RID OF EXTRA DATA FILES
cleanup()
{
	echo "Caught Signal ... cleaning up."
		if !(rm -f Data/.locked > /dev/null); then
       			{
               		 exit 1
			
        		} 
		fi
	kill ${rm_id}	
	clean_temp_data 

	echo "Done cleanup ... quitting."
	exit 1
}

#COMMAND TO 
#BEGIN WRITE
#THIS FUNCTION HANDELS READ RIGHT HANDSHAKES BETWEEN VARIOUS DRIVERS
#IN GENERAL, THE DATA IS PLACED IN THE VARIABLE $TIMESTAMP PRIOR TO CALL
#NEXT, IT OPENS THE DATA DIRECTORY AND LOOKS FOR THE .locked FILE
#IF IT EXISTS, IT HANGS OUT UNTIL IT DOESN'T EXIST. AT THAT POINT
#IT CREATES A .locked FILE, AND APPENDS TO THE DATA RECORD.
#FINALLY IT REMOVES THE .locked FILE IT HAS CREATED.
#THIS FUNCTION ALSO PARSES THE .DISABLED FILE IN THE DRIVER FOLDER
#AND TAKES A CHANNEL OFF LINE BY PREPENDING --DISABLED-- TO EACH LINE OF CONTENT IN THE DATA DIRECTORY
#written by MJV
write()
{
#CONFIRM THAT THERE IS NO HIDDEN FILE CALLED '.locked'
	while [ -e "Data/.locked" ];
		do
			sleep .2;
		done	
	echo "LOCKED" > "Data/.locked";
	#PARSE THE .disabled File
	channel_status=`cat "$DIR/.disabled${instance}"`
	#IF THE FILE DOSEN'T EXIT OR IS NOT ACCESIBLE
	#MAKES SURE A VALUE OF 0 IS USED
	if [ `expr $channel_status + 0` -eq 1 ]; then
		if !(echo "$data" | sed 's/^/'$timestamp'/g'| sed 's/$/'\-\-DISABLED\-\-'/g' >> "Data/$datafile" ); then
			{
			echo "GENERAL FAILURE WRITING TO RECORD: $#";
			cleanup;
			}
		fi
	else
		if !(echo "$data" | sed 's/^/'$timestamp'/g' >> -a "Data/$datafile"); then
			{
			echo "GENERAL FAILURE WRITING TO RECORD: $#";
			cleanup;
			}
		fi
	
	fi
	if !(rm -f "Data/.locked" > /dev/null); then
		{
			echo "GENERAL FAILURE REMOVING LOCK: $#";
			exit 1;	
		}
	fi
	if !(timestamp="" && data=""); then
		{
		echo "GENERAL FAILURE CLEARING WRITE BUFFER: $#";
		cleanup;
		}
	fi	
}
	
#THIS IS THE ACTUAL COMMUNICATION WITH THE INSTRUMENT
#THE TIMER CONTROL. AT THE BEGINING IT TESTS FOR THE 
#EXISTENCE IF TOGGLE VARRIABLES WHICH ARE UTILIZED BOTH BY
#THE COMM ROUTINE runit() AND THE DIAGNOSTICS DATA ROUTINE
#diag()

#THIS IS THE FUNCTION RUN IN THE EVENT THAT THE REQUIRED PARAMETERS
#ARE NOT ENTERED.
usage()
{
clear
cat << EOF
usage: $0 options
OPTIONS:

-r	rprt_nm [rn]
-d	dvc_prt [eg, /dev/ttyS0, /dev/ttyUSB1] 
-b	bd_rt [2400,4800,9600,38400etc.]
-o	occurrence number of (1 for primary, 2 for collocated)

Last updated 5/31/2013
EOF
}
#HELP FUNCTION GIVES BACKGROUND ON THIS DRIVER
help_me ()
{
clear
cat .help
exit 0
}
def_opts ()
{
clear
cat .options
}

##CLEAR ALL VARIABLES               
rprt_nm= ; dvc_prt= ; bd_rt= ; cmnd1= ; wt_rsp1= ; bd_rt= ; rsp_lngth= ; izs_val= ;
dvc_prt= ; frqncy= ; dtr= ; ctr= ; p8n1= ; izs= ; saroad= ; p8n1= ; id_nmbr= ; 
upp_flow=880 ; low_flow=720 ; instance=1; occurrence= ; recovery=0; min_count=0
##INITIALIZE THE BUFFER
## return='NOT WRITTEN TO'
##loop through all variables and parameters
##Note that the position of the colon indicates the presence
##of a parameter to collect. The h parameter simply
##returns the help message.

while getopts â€œhr:o:s:d:b:I:â€ OPTION
do
case $OPTION in
s)
saroad=$OPTARG
;;
r)
rprt_nm=$OPTARG
;;
d)
dvc_prt=$OPTARG
;;
b)
bd_rt=$OPTARG
;;
o)
occurrence=$OPTARG
;;
h)
usage
exit 1
;;
I)
instance=$OPTARG
;;
*)
usage
exit 1
;;
esac
done
#CHECK FOR THE CRITICAL PARAMETERS, IF THEY ARE NOT PRESENT THEN
#RUN THE USAGE FUNCTION WHICH RETURNS THE INSTRUCTIONS FOR PROPER USAGE
#MUST HAVE r n d b s
if [ -z "$rprt_nm" ] || [ -z "$dvc_prt" ] || [ -z "$bd_rt" ] || [ -z "$saroad" ] || [ -z "$occurrence" ]
	then
		{
		usage
		exit
		}
fi
	#INITIALIZED THE RAN VARIABLE. THIS IS USED TO TOGGLE THE TIMER GATE
ran=0
	#TRAP CTRL+C
trap cleanup 1 2 3 6 15
#start the 81000
record
#SETUP THE OPERATING LOOP
while :
do
second=`date "+%S"`
if [ "$second" -eq "01" ] && [ "$ran" -eq "0" ]; then
	{
	
	

	analysis()
		{	
			#VARIABLES TO INITIALIZE DATA ANALYSIS
			previous_minute=`date -d "last minute" "+%M"`
			previous_hour=`date -d "last minute" "+%H"`
			this_minute_path="${DIR}/${previous_hour}/${previous_minute}.dat"	
			#VARIABLES TO INITIALIZE FILE MAINTENANCE
			#future_minute=`date -d "next minute" "+%M"`		
			#future_hour=`date -d "next minute" "+%H"`		
			#old_minute=`date -d "last hour" "+%H"`
			#old_hour=`date -d "last hour" "+%H"`
			if ! [ -e "$this_minute_path" ]; then
				{
					echo "Analysis not performed, no data ready."
				}
			#PER REGGIE SMITH, WON'T REPORT FOR LESS THAN 75% OF THE DATA POINTS (45)
			elif [ `wc -l $this_minute_path | awk '{ print $1 }'` -lt 45 ]; then
				{
					echo "Partial minute, skipping."
					stamp=`date -d "last minute"`
					#REPORT SKIPPED MINUTES TO THE CARBLOGGER EMAIL ALERT SYSTEM
					echo "${rprt_nm}_${occurrence}::${stamp}::The ${rprt_nm}_${occurrence} data was not aggregated for this minute because of too few valid data points" >> "Data/errors$previous_hour"
				}
			elif [ `wc -l $this_minute_path | awk '{ print $1 }'` -gt 60 ]; then
				{
					echo "Too many data points for this minute, skipping."
					stamp=`date -d "last minute"`
					#REPORT SKIPPED MINUTES TO THE CARBLOGGER EMAIL ALERT SYSTEM
					echo "${rprt_nm}_${occurrence}::${stamp}::The ${rprt_nm}_${occurrence} data was not aggregated for this minute because of too many valid data points" >> "Data/errors$previous_hour"
				}	
			else
				{
					# OUTPUT RATE 1/n Hz
				
					ccount='0'
				for i in HOUR MINUTE SECOND NANOSECOND 'date' 'time' CO N20 H20 CO_dry N2O_dry GasP GasT AmbT cal;
					do
							
							ccount=`echo "$ccount+1" | bc`
							if [ "$ccount" -gt 6 ]; then
							{			
							
							#Date stamp
							today=`date -d "last minute" "+%Y-%d-%m"`
							timestamp=${rprt_nm}_${occurrence}::`date -d "last minute" "+%m-%d-%Y_${previous_hour}:${previous_minute}"`:::
							#THIS IS THE NAME OF THE CARBLOGGER DATA FILE RIGHT NOW
							datafile="$saroad-$today"
							#CALIBRATION SEQUENCE
								if [ "$ccount" -eq 15 ]; then
									{
										#TALK TO THE INSTRUMENT, PRE-APPEND THE TIMESTAMP AND REPORTING NAME TO EACH
										resultset=`gawk -f sys_resources/stats.nawk $ccount $this_minute_path`
										#ONLY USE AVERAGE. IF YOU WANT -- UNCOMMENT						
										token=`echo "${resultset}" | awk '{ print $2+0 }'`
										if [[ $token < 8 ]]; then
										{
											recovery=4
											
											if [[ $min_count < 7 ]]; then
											{
											
												echo "${timestamp} Virtual environics9100 equilibration $token $recovery $min_count cal=66" >> Data/${datafile}
												min_count=`echo "$min_count+1" | bc`

											}
											
											elif [[ $token > 7 ]] && [[ $token < 8 ]] && [[ $min_count > 6 ]]; then
											{
											
												echo "${timestamp} Virtual environics9100 half-cal minute $token $recovery $min_count cal=66" >> Data/${datafile}
											
											}
											else
											{
											
												echo "${timestamp} Virtual environics9100 precision $token $recovery $min_count cal=12" >> Data/${datafile}
											
											}
											fi										
										
										}
										else
										{
											recovery=`echo "$recovery-1" | bc`
											if [ "$recovery" -gt 0 ]; then
												{
												echo "${timestamp} Virtual environics9100 recovery $token $recovery $min_count cal=66" >> Data/${datafile}
												}
											else
												{
												echo "${timestamp} Virtual environics9100 sample $token $recovery $min_count cal=0" >> Data/${datafile}	
												recovery="0"
												min_count="0"
												}
											fi
										}
										fi	
									}
								else
									{
										dsbld_stt=`cat ${DIR}/.disabled${instance}`
										if [ $dsbld_stt == "0" ]; then
											{
												fld_var=''
												:
											}
										else
											{
												fld_var='--DISABLED--'
											}
										fi
										#TALK TO THE INSTRUMENT, PRE-APPEND THE TIMESTAMP AND REPORTING NAME TO EACH
										resultset=`gawk -f sys_resources/stats.nawk $ccount $this_minute_path`
										#ONLY USE AVERAGE. IF YOU WANT -- UNCOMMENT						
										token=`echo "${resultset}" | awk '{ print $2 }'`
										echo "${timestamp} Avg_${i}_${occurrence}=${token} ${fld_var}" >> Data/${datafile} 
									}
								fi
							}
							else
							{
							:
							}
							fi
					done			
				}
			fi
	}

	
	#RUN THE ANALYSIS FUNCTION
		analysis
	#TOGGLE THE RAN VARIABLE SO THAT THE PROCESS WILL NOT REPEAT
	#UNTIL THE BEGINNING OF THE NEXT MINUTE.
		ran=1
	#WAIT FOR COMPLETION OF THE RUNIT FUNCTION AND THE VARIABLE
	#SET
		sleep 1
	}
	#AND WAIT ONE SECOND BEFORE CHECKING AGAIN
else 
	{
	#WAIT ONE SECOND
		sleep .5
	#SET RAN TO 0
		ran=0
	}
fi
done;
exit;


